package com.example.musicplayer.util

import android.content.Context
import com.example.musicplayer.model.Song
import com.google.gson.Gson

object HistoryManager {
    private const val HISTORY_PREF_NAME = "history_prefs"
    private const val HISTORY_KEY = "history_key"

    fun saveSong(context: Context, song: Song) {
        val prefs = context.getSharedPreferences(HISTORY_PREF_NAME, Context.MODE_PRIVATE)
        val editor = prefs.edit()
        val history = getHistory(context).toMutableList()

        // 检查是否已经存在相同的歌曲
        if (!history.any { it.audioPath == song.audioPath }) {
            history.add(song)
            editor.putString(HISTORY_KEY, Gson().toJson(history))
            editor.apply()
        }
    }

    fun getHistory(context: Context): List<Song> {
        val prefs = context.getSharedPreferences(HISTORY_PREF_NAME, Context.MODE_PRIVATE)
        val historyJson = prefs.getString(HISTORY_KEY, "[]")
        return Gson().fromJson(historyJson, Array<Song>::class.java).toList()
    }

    fun clearHistory(context: Context) {
        val prefs = context.getSharedPreferences(HISTORY_PREF_NAME, Context.MODE_PRIVATE)
        prefs.edit().remove(HISTORY_KEY).apply()
    }
}